package com.cg.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.cg.controller.UploadController;


@Component
public class UploadUtil {
	
	/**访问地址*/
	@Value("${global.upload.path}")
	private String path;

    /**
     * 上传
     * @param request
     * @return
     * @throws Exception
     */
    public List<String> upload(HttpServletRequest request,String docBase, String filepath,String folderName) {
    	List<String> filepaths = new ArrayList<>();
		 //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
        	//转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
            	//取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null) {
                	try {
                		File forlder = new File(docBase+folderName); 
                		if(!forlder.exists()){
                			forlder.mkdirs();
                		}
                		String path= docBase+folderName+ file.getOriginalFilename().split("\\\\")[file.getOriginalFilename().split("\\\\").length-1];
						file.transferTo(new File(path));
						filepaths.add(filepath+folderName+file.getOriginalFilename());
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
            }
        }
		return filepaths;
	}
    
    /**
	 * 上传图片
	 * @param request
	 * @param menu
	 */
	public String uploadImg(HttpServletRequest request,String mypath){
		String docBase = UploadController.class.getClassLoader().getResource("").getPath();
		//创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
       	   //转换成多部分request
           MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
           //取得request中的所有文件名
           Iterator<String> iter = multiRequest.getFileNames();
           while (iter.hasNext()) {
           	   //取得上传文件
               MultipartFile file = multiRequest.getFile(iter.next());
               if (file != null&&file.getOriginalFilename()!=null&&file.getOriginalFilename().length()>0) {
					final ByteArrayOutputStream srcImageData = new ByteArrayOutputStream();
					try {
						IOUtils.copy(file.getInputStream(), srcImageData);
						File dir = new File(docBase+"static/"+mypath);
						if(!dir.exists()){dir.mkdirs();}
						int lengh = file.getOriginalFilename().split("\\\\").length;
						String fileName = file.getOriginalFilename().split("\\\\")[lengh-1];
						// 上传图片
						FileUtils.copyInputStreamToFile(new ByteArrayInputStream(srcImageData.toByteArray()), new File(dir,fileName));
//						menu.setImgUrl(path+"appmenu/"+menu.getCode()+"/"+fileName);
						return path+mypath+fileName;
					} catch (IOException e) {
						e.printStackTrace();
						return "";
					}
				}
               
           	}
           
        }
        return "";
	}
    
    

    /**
     * 获取文件绝对路径
     * @param request
     * @param host
     * @return
     */
    public static String getFileUrl(HttpServletRequest request, String host) {
        String path = request.getScheme() + "://" + host + request.getContextPath() + "/";
        int port = request.getServerPort();
        if (80 != port) {
            path = request.getScheme() + "://" + host + ":" + request.getServerPort() + request.getContextPath() + "/";
        }
        return path;
    }

    /**
     * 文件路径
     * @param type
     * @return
     */
    public String getFilePath(String filepath, String filename) {
    	StringBuilder sb = new StringBuilder(filepath).append(DateUtils.format(new Date())).append("/").append(filename);
        return sb.toString();
    }
    
    /**
     * 文件重命名
     * @param suffixes
     * @return
     */
    public String getNewName(String suffixes){
    	return UUID.randomUUID().toString() + suffixes;
    }

    /**
     * 删除文件
     * @param path
     */
    public static void delFiles(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }
}
